from rest_framework_jwt.settings import api_settings

from meiduo_mall import settings
from oauth.models import OAuthQQUser
from oauth.serializers import QQAuthUserSerializer
from QQLoginTool.QQtool import OAuthQQ

from oauth.utils import generic_openid_token

from rest_framework.response import Response
from rest_framework.views import APIView


class OauthQQUrlAPIView(APIView):
    # /oauth/qq/statues/
    def get(self,request):

        # auth_url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=test'
        # state = 'test'
        state = '/'

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        auth_url = qq.get_qq_url()

        return Response({'auth_url':auth_url})



class OAuthQQUserAPIView(APIView):
    # serializer_class = serializers.QQAuthUserSerializer
    def get_token(self,user):
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'user_id': user.id,
            'username': user.username,
            'token': token
        })
    def get(self,request):
        # 1. 接收code
        code = request.query_params.get('code')
        if code is None:
            from rest_framework import status

            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 2. 通过code换取token （是我们通过 请求 向腾讯的服务器换）

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)
        token = qq.get_access_token(code)

        # 3. 通过token换取openid (openid是此网站上唯一对应用户身份的标识)
        openid = qq.get_open_id(token)

        # 4. 我们需要根据openid进行判断 （根据openid进行查询）
        # 如果用户绑定过，则直接登陆
        # 如果用户没有绑定过，则进行绑定
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 说明不存在， 就应该绑定

            openid_token = generic_openid_token(openid)

            return Response({'access_token': openid_token})
        else:
            # 说明存在， 存在应该登陆
            # 返回 token，username,userid

            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                'user_id': qquser.user.id,
                'username': qquser.user.username,
                'token': token
            })
            # return self.get_token(qquser)

    def post(self,request):
        """openid绑定到用户"""
        data = request.data

        # 获取序列化器对象
        serializer = QQAuthUserSerializer(data=data)
        # 开启校验
        serializer.is_valid(raise_exception=True) # raise_exception=True
        # 保存校验结果，并接收

        user = serializer.save()

        # 生成JWT token，并响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })

        return response
